package myJs.cps

import cats.effect.SyncIO
import myJs.Implicits._
import myJs.myPkg.reactHookForm.{ReactHookForm, UseFormStateOptions}
import myJs.tool.Tool
import myJs.tool.Tool._

import scala.scalajs.js
import japgolly.scalajs.react.vdom.all._
import japgolly.scalajs.react._
import japgolly.scalajs.react.React.Fragment
import japgolly.scalajs.react.util.EffectCatsEffect._
import myJs.Utils._
import myJs.myPkg.Hooks._

/** Created by yz on 3/11/2020
  */
object InputCp {

  case class Props(
      value: String = "",
      onChange: String => SyncIO[Unit] = v=>SyncIO{},
      show: Boolean = false,
      label: String = "",
      name: String,
      questionInfo: String = ""
  ){
    @inline def render: VdomElement = {
      Component(this)
    }
  }

  val Component = ScalaFnComponent[Props] { props =>
    val formState = ReactHookForm.useFormState(options =
      UseFormStateOptions(
        name = props.name
      )
    )
    useEffect(
      SyncIO{
        Tool.popover
        ()
      },
      List()
    )

    val hasErrorCls =
      if (formState.errors.deepDefinedAt(props.name)) "has-error"
      else ""
    val displayStr =
      if (props.show) "block" else "none"
    div(
      display := displayStr,
      className := s"form-group col-sm-12 ${hasErrorCls}",
      label(
        className := s"",
        s"${props.label}",
        if (props.questionInfo.nonBlank) {
          span(
            className := "",
            a(
              `type` := "button",
              className := "selfQuestion",
              title := messages("note"),
              dataContainer:="body",
              dataToggle := "popover",
              dataHtml := "true",
              dataPlacement := "left",
              dataContent := props.questionInfo,
              i(className := "fa fa-question-circle-o")
            )
          )
        } else EmptyVdom,
        ":"
      ),
      PureInputCp.Props(
        name = s"${props.name}Show",
        value = s"${props.show}",
        `type` = "hidden"
      ).render,
      PureInputCp.Props(
        name = props.name,
        value = props.value,
        onChange = props.onChange
      ).render
    )

  }

}
